/*================================================================
*   Copyright (C) 2024 baichao All rights reserved.
*
*   文件名称：main.cpp
*   创 建 者：baichao
*   创建日期：2024年09月23日
*   描    述：
*
================================================================*/

#include <argp.h>
#include <stdio.h>

const char *argp_program_version = "example 1.0";
const char *argp_program_bug_address = "<bug@example.com>";

/* Program documentation. */
static char doc[] = "这是一个Argp的简单示例。";

/* A description of the arguments we accept. */
static char args_doc[] = "ARG1 [STRING...]";

/* The options we understand. */
static struct argp_option options[] = {{"output", 'o', "FILE", 0, "输出文件"},
                                       {"verbose", 'v', 0, 0, "显示详细信息"},
                                       {0}};

/* Used by main to communicate with parse_opt. */
struct arguments {
  char *output_file;
  int verbose;
  char *args[2];
};

/* Parse a single option. */
static error_t parse_opt(int key, char *arg, struct argp_state *state) {
  struct arguments *arguments = (struct arguments *)state->input;

  switch (key) {
    case 'o':
      arguments->output_file = arg;
      break;
    case 'v':
      arguments->verbose = 1;
      break;
    case ARGP_KEY_ARG:
      if (state->arg_num >= 2) /* Too many arguments. */
        argp_usage(state);
      arguments->args[state->arg_num] = arg;
      break;
    case ARGP_KEY_END:
      if (state->arg_num < 2) /* Not enough arguments. */
        argp_usage(state);
      break;
    default:
      return ARGP_ERR_UNKNOWN;
  }
  return 0;
}

/* Our argp parser. */
static struct argp argp = {options, parse_opt, args_doc, doc};

int main(int argc, char **argv) {
  struct arguments arguments;

  /* Default values. */
  arguments.output_file = "-";
  arguments.verbose = 0;

  /* Parse our arguments; every option seen by parse_opt will be
     reflected in arguments. */
  argp_parse(&argp, argc, argv, 0, 0, &arguments);

  printf("OUTPUT_FILE = %s\nVERBOSE = %s\nARG1 = %s\nARG2 = %s\n",
         arguments.output_file, arguments.verbose ? "yes" : "no",
         arguments.args[0], arguments.args[1]);

  return 0;
}
